package com.junzhiit.nengji.app.service.impl;

import java.util.Date;
import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.bainaeco.framework.util.DateUtil;
import com.junzhiit.nengji.app.service.CommissionHistoryService;
import com.junzhiit.nengji.app.service.IncomeHistoryService;
import com.junzhiit.nengji.app.service.SellSetingService;
import com.junzhiit.nengji.app.web.util.Constants;
import com.junzhiit.nengji.bo.OrdersBO;
import com.junzhiit.nengji.dao.BenefitSettingDAO;
import com.junzhiit.nengji.dao.CommissionHistoryDAO;
import com.junzhiit.nengji.dao.GoodsDataHistoryDAO;
import com.junzhiit.nengji.dao.OrdersDAO;
import com.junzhiit.nengji.dao.OrdersDataHistoryDAO;
import com.junzhiit.nengji.dao.SellLevelDAO;
import com.junzhiit.nengji.dao.ShopDAO;
import com.junzhiit.nengji.dao.SystemConfigDAO;
import com.junzhiit.nengji.dao.UserConfigDAO;
import com.junzhiit.nengji.dao.UserDAO;
import com.junzhiit.nengji.model.BenefitSetting;
import com.junzhiit.nengji.model.CommissionHistory;
import com.junzhiit.nengji.model.GoodsDataHistory;
import com.junzhiit.nengji.model.OrdersDataHistory;
import com.junzhiit.nengji.model.SellLevel;
import com.junzhiit.nengji.model.SellSeting;
import com.junzhiit.nengji.model.Shop;
import com.junzhiit.nengji.model.SystemConfig;
import com.junzhiit.nengji.model.User;
import com.junzhiit.nengji.model.UserConfig;
import com.junzhiit.nengji.model.enums.Is;
import com.junzhiit.nengji.model.enums.OrdersDataHistoryStatus;

@Service
public class CommissionHistoryServiceImpl extends BaseServiceImpl implements CommissionHistoryService {

	@Autowired
	private OrdersDAO ordersDAO;
	
	@Autowired 
	private SellLevelDAO sellLevelDAO;
	
	@Autowired
	private UserDAO userDAO;
	
	@Autowired
	private SellSetingService sellSetingService;
	
	@Autowired
	private BenefitSettingDAO benefitSettingDAO;
	
	@Autowired
	private CommissionHistoryDAO commissionHistoryDAO;
	
	@Autowired
	private SystemConfigDAO systemConfigDAO;
	
	@Autowired
	private IncomeHistoryService incomeHistoryService;
	
	@Autowired
	private UserConfigDAO uerConfigDAO;
	
	@Autowired
	private OrdersDataHistoryDAO ordersDataHistoryDAO;
	
	@Autowired
	private GoodsDataHistoryDAO goodsDataHistoryDAO;
	
	@Autowired
	private UserConfigDAO userConfigDAO;
	
	@Autowired
	private ShopDAO shopDAO;
	
	
	@Override
	public void countCommission() {
		SellSeting sellSeting = sellSetingService.findSellSeting();
		SystemConfig systemConfig = systemConfigDAO.find();
		int maxLevel = 0;
		if(sellSeting.getIsOpenSell() != null && sellSeting.getIsOpenSell() == Is.YES.toIntValue()){
			maxLevel = sellLevelDAO.getSellLevelMax();
			Date date = DateUtil.parseDate(DateUtil.addDays(new Date(),-6), DateUtil.DATE_PATTERN_DEFAULT);
			List<OrdersBO> list = ordersDAO.getOrderByConfirmTime(date,Is.YES.toIntValue());
			for(OrdersBO orders : list){
				
				Double sumGoodsMoney = orders.getPrice() * orders.getGoodsNumber();
				Double money = sumGoodsMoney - (sumGoodsMoney * orders.getProfit() / 100);
				
				Shop shop = shopDAO.query(orders.getShopId());
				shop.setWithdrawalMoney(shop.getWithdrawalMoney()+money);
				shop.setAccumulativeMoney(shop.getAccumulativeMoney()+money);
				shop.setMonthIncomeMoney(shop.getMonthIncomeMoney()+money);
				if((shop.getWaitSumMoney() - money) > 0){
					shop.setWaitSumMoney(shop.getWaitSumMoney() - money);
				}
				shopDAO.update(shop);
				
				User user = userDAO.query(orders.getUserId());
				String parentId = user.getParentId();
				Integer level = 0;
				for (int i = 1; i <=maxLevel; i++) {
					if(StringUtils.isBlank(user.getParentId()) || user.getParentId().equals(Constants.MEMBER_PARENT_ID_ROOT))
						break;
					
					User parentMember = userDAO.query(parentId);
					if(parentMember!=null && StringUtils.isNotBlank(parentMember.getId())){
						parentId = parentMember.getParentId();
						level ++;
					}
				}
				if(level > 0){
					parentId = user.getParentId();
					for (int i = 1; i <=level; i++) {
						if(StringUtils.isBlank(parentId) || parentId.equals(Constants.MEMBER_PARENT_ID_ROOT))
							break;
						User parentUser = userDAO.query(parentId);
						if(parentUser!=null && StringUtils.isNotBlank(parentUser.getId())){
							if(systemConfig.getIsOpenMemberSell() == Is.YES.toIntValue()){
								if(maxLevel == i){
									if(parentUser.getIsMemberSell() != Is.YES.toIntValue()){
										break;
									}
								}
							}
							SellLevel sellLevel = sellLevelDAO.findByLevel(i);
							BenefitSetting benefitSetting = benefitSettingDAO.findBenefit(orders.getProfit());
							if(sellLevel!=null && sellLevel.getValue()!=null){
								Double value = (((orders.getPrice()*orders.getGoodsNumber()) * (orders.getProfit()/100))* benefitSetting.getValue()/100 )*sellLevel.getValue()/100;
								CommissionHistory commissionHistory = new CommissionHistory();
								commissionHistory.setIncomeUserId(parentId);
								commissionHistory.setTransactionUserId(user.getId());
								commissionHistory.setCommissionMoney(value);
								commissionHistory.setCommissionLevle(i);
								commissionHistory.setCommissionRation(sellLevel.getValue());
								commissionHistory.setOrderGoodsId(orders.getOrderGoodsId());
								commissionHistory.setOrderNumber(orders.getOrderNumber());
								commissionHistory.setOrderId(orders.getId());
								commissionHistory.setIncomeType(parentUser.getIsShop());
								commissionHistory.setGoodsId(orders.getGoodsId());
								commissionHistory.setGoodsNumber(orders.getGoodsNumber());
								commissionHistory.setGoodsPrice(orders.getPrice());
								commissionHistory.setTransactionType(orders.getType());
								commissionHistory.setEventType(orders.getIsOpenRebate());
								commissionHistory.setPayMoney(orders.getPayMoney());
								commissionHistory.setPsValue(orders.getProfit());
								commissionHistory.setPsRation(benefitSetting.getValue());
								commissionHistoryDAO.insert(commissionHistory);
								
								UserConfig userConfig = uerConfigDAO.getUserConfig(parentId);
								if(StringUtils.isNoneBlank(userConfig.getId())){
									userConfig.setSellMoney(userConfig.getSellMoney() + value);
									userConfig.setWithdrawalMoney(userConfig.getWithdrawalMoney()+value);
									uerConfigDAO.update(userConfig);
								}
								
								//更新资产明细及财务报表
								OrdersDataHistory ordersDataHistory = ordersDataHistoryDAO.findByOrderId(orders.getId());
								if(ordersDataHistory != null){
									ordersDataHistory.setShareBenefitMoney(ordersDataHistory.getShareBenefitMoney()+value);
									ordersDataHistory.setStatus(Is.YES.toIntValue());
									ordersDataHistoryDAO.update(ordersDataHistory);
									
									List<GoodsDataHistory> goodsDataHistoriesList = goodsDataHistoryDAO.findList(ordersDataHistory.getId());
									for(GoodsDataHistory params : goodsDataHistoriesList){
										GoodsDataHistory goodsDataHistory = goodsDataHistoryDAO.query(params.getId());
										if(goodsDataHistory != null){
											User parentMember = userDAO.query(parentId);
											if(i == 1){
												goodsDataHistory.setPrimaryBenefitId(parentId);
												goodsDataHistory.setPrimaryBenefitName(parentMember.getNickName());
												goodsDataHistory.setPrimaryBenefitRation(sellLevel.getValue());
												goodsDataHistory.setPrimaryBenefitMoney(value);
											}else if(i == 2){
												goodsDataHistory.setSecondBenefitId(parentId);
												goodsDataHistory.setSecondBenefitName(parentMember.getNickName());
												goodsDataHistory.setSecondBenefitRation(sellLevel.getValue());
												goodsDataHistory.setSecondBenefitMoney(value);
											}
											goodsDataHistoryDAO.update(goodsDataHistory);
											
											GoodsDataHistory goodsDataHistoryParams = goodsDataHistoryDAO.query(goodsDataHistory.getId());
											Double profit = goodsDataHistoryParams.getPrice()*goodsDataHistoryParams.getNumber() - goodsDataHistoryParams.getShopMoney(); //利润
											//共分出多少钱
											Double sumMoney = goodsDataHistoryParams.getReferrerMoney() +  goodsDataHistoryParams.getPrimaryBenefitMoney()+goodsDataHistoryParams.getSecondBenefitMoney()+goodsDataHistoryParams.getShopGetBenefitMoney();
											Double grossMargin = profit - sumMoney; //毛利
											Double grossMarginRate = grossMargin / profit * 100;//毛利率
											if(!grossMarginRate.isNaN()){
												goodsDataHistoryParams.setGrossMargin(grossMargin);
												goodsDataHistoryParams.setGrossMarginRate(grossMarginRate);
											}
											goodsDataHistoryDAO.update(goodsDataHistoryParams);
										}
									 }
								}
							}
							parentId = parentUser.getParentId();
						}
					}
				}
				incomeHistoryService.addIncomeHistory(orders, user.getParentId());
				
				//统计毛利
				OrdersDataHistory ordersDataHistory = ordersDataHistoryDAO.findByOrderId(orders.getId());
				if(ordersDataHistory != null){
					Double profit = ordersDataHistory.getPayMoney() - ordersDataHistory.getPostage() - ordersDataHistory.getShopMoney();
					Double sumMoney = ordersDataHistory.getShareBenefitMoney() + ordersDataHistory.getReferrerMoney()+ordersDataHistory.getAgencyBenefit() + ordersDataHistory.getAgencyAccount();
					Double grossMargin = profit - sumMoney; //毛利
					Double grossMarginRate = grossMargin / profit * 100;//毛利率
					if(!grossMarginRate.isNaN()){
						ordersDataHistory.setGrossMargin(grossMargin);
						ordersDataHistory.setGrossMarginRate(grossMarginRate);
					}
					ordersDataHistoryDAO.update(ordersDataHistory);
				}
			}
			
		}
	}

	@Override
	public void add(String userId, String orderGoodsId,String parentId,String orderDataHistoryId) {
		User user = userDAO.query(userId);
		SystemConfig systemConfig = systemConfigDAO.find();
		SellSeting sellSeting = sellSetingService.findSellSeting();
		if(systemConfig == null && sellSeting == null){
			return;
		}
		int maxLevel = 0;
		if(sellSeting.getIsOpenSell() != null && sellSeting.getIsOpenSell() == Is.YES.toIntValue()){
			maxLevel = sellLevelDAO.getSellLevelMax();
			List<OrdersBO> list = ordersDAO.findOrderByid(orderGoodsId);
			for(OrdersBO orders : list){
				Integer level = 0;
				for (int i = 1; i <=maxLevel; i++) {
					if(StringUtils.isBlank(user.getParentId()) || user.getParentId().equals(Constants.ROOT_VALUE))
						break;
					
					User parentMember = userDAO.query(parentId);
					if(parentMember!=null && StringUtils.isNotBlank(parentMember.getId())){
						parentId = parentMember.getParentId();
						level ++;
					}
				}
				if(level > 0){
					parentId = user.getParentId();
					for (int i = 1; i <=level; i++) {
						if(StringUtils.isBlank(parentId) || parentId.equals(Constants.ROOT_VALUE))
							break;
						User parentUser = userDAO.query(parentId);
						if(parentUser!=null && StringUtils.isNotBlank(parentUser.getId())){
							if(systemConfig.getIsOpenMemberSell() == Is.YES.toIntValue()){
								if(maxLevel == i){
									if(parentUser.getIsMemberSell() != Is.YES.toIntValue()){
										break;
									}
								}
							}
							SellLevel sellLevel = sellLevelDAO.findByLevel(i);
							BenefitSetting benefitSetting = benefitSettingDAO.findBenefit(orders.getProfit());
							if(benefitSetting == null){
								return;
							}
							if(sellLevel!=null && sellLevel.getValue()!=null){
								
								Double value = ((orders.getPrice()*orders.getGoodsNumber()) * orders.getProfit()/100 *  benefitSetting.getValue()/100)*sellLevel.getValue()/100;
								CommissionHistory commissionHistory = new CommissionHistory();
								commissionHistory.setIncomeUserId(parentId);
								commissionHistory.setTransactionUserId(user.getId());
								commissionHistory.setCommissionMoney(value);
								commissionHistory.setCommissionLevle(i);
								commissionHistory.setCommissionRation(sellLevel.getValue());
								commissionHistory.setOrderGoodsId(orders.getOrderGoodsId());
								commissionHistory.setOrderNumber(orders.getOrderNumber());
								commissionHistory.setOrderId(orders.getId());
								commissionHistory.setIncomeType(parentUser.getIsShop());
								commissionHistory.setGoodsId(orders.getGoodsId());
								commissionHistory.setGoodsNumber(orders.getGoodsNumber());
								commissionHistory.setGoodsPrice(orders.getPrice());
								commissionHistory.setTransactionType(orders.getType());
								commissionHistory.setEventType(orders.getIsOpenRebate());
								commissionHistory.setPayMoney(orders.getPayMoney());
								commissionHistory.setPsValue(orders.getProfit());
								commissionHistory.setPsRation(benefitSetting.getValue());
								commissionHistoryDAO.insert(commissionHistory);
								
								//更新用户分销金额
								UserConfig userConfig = userConfigDAO.getUserConfig(parentId);
								if(StringUtils.isNoneBlank(userConfig.getId())){
									userConfig.setSellMoney(userConfig.getSellMoney() + value);
									userConfig.setPileSellMoney(userConfig.getPileSellMoney()+value);
									userConfig.setWithdrawalMoney(userConfig.getWithdrawalMoney()+value);
									userConfigDAO.update(userConfig);
								}
								
								//更新资产明细及财务报表
								OrdersDataHistory ordersDataHistory = ordersDataHistoryDAO.query(orderDataHistoryId);
								if(ordersDataHistory != null){
									ordersDataHistory.setShareBenefitMoney(ordersDataHistory.getShareBenefitMoney()+value);
									ordersDataHistory.setStatus(OrdersDataHistoryStatus.COMPLETE.toIntValue());
									ordersDataHistoryDAO.update(ordersDataHistory);
								}
								
								List<GoodsDataHistory> goodsList = goodsDataHistoryDAO.findList(orderDataHistoryId);
								for(GoodsDataHistory goodsDataHistory : goodsList){
									if(goodsDataHistory != null){
										User parentMember = userDAO.query(parentId);
										if(i == 1){
											goodsDataHistory.setPrimaryBenefitId(parentId);
											goodsDataHistory.setPrimaryBenefitName(parentMember.getNickName());
											goodsDataHistory.setPrimaryBenefitRation(sellLevel.getValue());
											goodsDataHistory.setPrimaryBenefitMoney(value);
										}else if(i == 2){
											goodsDataHistory.setSecondBenefitId(parentId);
											goodsDataHistory.setSecondBenefitName(parentMember.getNickName());
											goodsDataHistory.setSecondBenefitRation(sellLevel.getValue());
											goodsDataHistory.setSecondBenefitMoney(value);
										}
										goodsDataHistoryDAO.update(goodsDataHistory);
									}
								}
							}
							parentId = parentUser.getParentId();
						}
					}
				}else{
					//更新资产明细及财务报表
					OrdersDataHistory ordersDataHistory = ordersDataHistoryDAO.query(orderDataHistoryId);
					if(ordersDataHistory != null){
						ordersDataHistory.setStatus(OrdersDataHistoryStatus.COMPLETE.toIntValue());
						ordersDataHistoryDAO.update(ordersDataHistory);
					}
				}
				incomeHistoryService.addIncomeHistory(orders, user.getParentId());
				
				OrdersDataHistory newOrdersDataHistory =  ordersDataHistoryDAO.query(orderDataHistoryId);
				if(newOrdersDataHistory != null){
					Double profit = newOrdersDataHistory.getPayMoney()- newOrdersDataHistory.getPostage() - newOrdersDataHistory.getShopMoney();
					Double sumMoney = newOrdersDataHistory.getShareBenefitMoney() + newOrdersDataHistory.getReferrerMoney()+newOrdersDataHistory.getAgencyBenefit() + newOrdersDataHistory.getAgencyAccount();
					Double grossMargin = profit - sumMoney; //毛利
					Double grossMarginRate = grossMargin / profit * 100;//毛利率
					if(!grossMarginRate.isNaN()){
						newOrdersDataHistory.setGrossMargin(grossMargin);
						newOrdersDataHistory.setGrossMarginRate(grossMarginRate);
					}
					ordersDataHistoryDAO.update(newOrdersDataHistory);
				}
			}
		}
		
	}
	
}
